package org.jeecg.common.util.mall;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpMessage;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;
import org.jboss.logging.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

/**
 * @author wq
 */
public class HttpUtils {

    private static Logger logger = Logger.getLogger(HttpUtils.class);

    private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();

    static {
        System.setProperty("jsse.enableSNIExtension", "false");
    }

    /**
     * 使用 http client 发起一个 post 请求
     *
     * @param url    url
     * @param heads  请求头
     * @param params 请求参数
     * @return 结果
     * @throws IOException e
     */
    public static String httpClientPost(
            String url,
            Map<String, String> heads,
            Map<String, String> params)
            throws IOException {
        String resp = "";
        CloseableHttpResponse response = null;
        HttpPost post = null;
        try {
            post = new HttpPost(url);
            logger.info("http client--> post: " + url + "?" + params);
            post.setConfig(requestConfig);
            // 设置请求头
            setHeaders(heads, post);
            List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
            // 设置请求参数
            if (params != null) {
                Set<String> paramsKeys = params.keySet();
                for (String key : paramsKeys) {
                    String value = params.get(key);
                    NameValuePair param = new BasicNameValuePair(key, value);
                    valuePairs.add(param);
                }
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
            post.setEntity(entity);
            response = httpClient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.info("http client--> post failed: " + response.getStatusLine());
            } else {
                resp = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }

        } catch (IOException e) {
           // throw new CustomException("http client--> post exception: " + e.getMessage(), 500);
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            if (post != null) {
                post.releaseConnection();
            }
        }
        logger.info("http client--> post: " + url + " Result: " + resp);
        return resp;
    }

    /**
     * 使用 http client 发起一个 get 请求
     *
     * @param url    url
     * @param params 请求参数
     * @return 结果
     * @throws IOException e
     */
    public static String httpClientGet(String url, String params) throws IOException {
        return httpClientGet(url, null, params);
    }

    /**
     * 使用 http client 发起一个 get 请求
     *
     * @param url   url
     * @param heads 请求头
     * @return 结果
     * @throws IOException e
     */
    public static String httpClientGet(String url, Map<String, String> heads) throws IOException {
        return httpClientGet(url, heads, null);
    }

    /**
     * 使用 http client 发起一个 get 请求
     *
     * @param url    url
     * @param heads  请求头
     * @param params 请求参数
     * @return 结果
     * @throws IOException e
     */
    public static String httpClientGet(String url, Map<String, String> heads, String params) throws IOException {
        String resp = "";
        CloseableHttpResponse response = null;
        try {
            if (!Strings.isBlank(params)) {
                url = url + "?" + params;
            }
            HttpGet get = new HttpGet(url);
            logger.info("http client--> get: " + url);
            get.setConfig(requestConfig);
            // 设置请求头
            setHeaders(heads, get);
            response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("http client--> get failed: " + response.getStatusLine());
            } else {
                resp = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            // throw new CustomException("http client--> get exception: " + e.getMessage(), 500);
            e.printStackTrace();
        }
        logger.info("http client--> get: " + url + " Result: " + resp);
        return resp;
    }


    private static void setHeaders(Map<String, String> heads, HttpMessage httpBase) {
        if (heads != null) {
            Set<String> keys = heads.keySet();
            for (String key : keys) {
                String value = heads.get(key);
                httpBase.setHeader(key, value);
            }
        }
    }

}